﻿
using Microsoft.AspNetCore.Mvc;
using WHLRDF.Code.BLL;
using WHLRDF.Code.Model;
using System.Collections.Generic;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using WHLRDF.Application.BLL;
using WHLRDF.ORM;

namespace WHLRDF.Code.Web.Controllers
{
    [MenuPage(10, "010", "服务器管理", "Code/home", "fa-database")]
    public class HomeController : AreaController
    {
        #region Service注入

        public IDbServerService mService { get; set; }
        public ISysFieldTypeService mSysDbTypeService { get; set; }
        public IDbColumnService mDbColumnService { get; set; }

        public IDbTableService mTService { get; set; }
        public IDbServerService mSService { get; set; }

        public IDbCodeService mCService { get; set; }

        public IDbFieldRelationTypeService dbTypeService { get; set; }

        public IDbTemplateService dTService { get; set; }
        #endregion
        [Permission]
        public IActionResult Index()
        {

            return View();
        }

        [HttpPost]
        [Permission(IsParent = true)]
        public JsonResult ForGrid(LigerGrid grid,string id)
        {
            grid.Rows= mCService.GetColumns( id);
            return Json(grid);
        }

        [Permission(IsParent = true)]
        public IActionResult Edit(string id, DbServerEntity entity)
        {

            return View();
        }
        [HttpPost]
        [Permission(NoAccess =true)]
        public JsonResult Delete(string deleteKeys)
        {
            return Json(AjaxResult.Success());
        }
        [Permission(ActionName = "DbDelete")]
        [HttpPost]
        public JsonResult DbColumnDelete(string deleteKeys)
        {
            string strError = "";
            if (mDbColumnService.Delete(deleteKeys, ref strError))
            {
                return Json(AjaxResult.Success());
            }
            else
            {
                return Json(AjaxResult.Error(strError));
            }
        }
        [Permission("01","删除")]
        [HttpPost]
        public JsonResult DbDelete(string sourceId, string dbServerType)
        {
            string strError = "";
            if (mCService.DbDelete(sourceId, dbServerType, ref strError))
            {
                return Json(AjaxResult.Success());
            }
            else
            {
                return Json(AjaxResult.Error(strError));
            }
        }
        [HttpPost]
        [Permission(IsParent = true)]
        public JsonResult GetTree(string parentid,string action="T",int dbServerType=0)
        {
            return Json(AjaxResult.Success(mCService.GetDbTrees(parentid, dbServerType, action)));

        }
        [HttpPost]
        [Permission(IsParent = true)]
        public JsonResult GetTreeTable(string id)
        {

            return Json(mCService.GetDbTable(id, true));
        }
        [HttpPost]
        [Permission(IsParent =true)]
        public JsonResult GetTreeView(string id)
        {

            return Json(mCService.GetDbTable(id, false));
        }
       
        [Permission("02","编辑",IsPost=true)]
        [HttpPost]
        public JsonResult SaveColumns(string list)
        {
            List<DbColumnEntity> lst = JSONHelper.FromJson <List<DbColumnEntity> >( list);
            string strError = "";

            if (mDbColumnService.Save(lst, ref strError))
            {
                return Json(AjaxResult.Success());
            }
            return Json(AjaxResult.Error(strError));
        }
      
        [Permission(IsPost =true,ActionName = "SaveColumns")]
        public IActionResult DbServer(DbServerEntity entity,string id)
        {
            if (!string.IsNullOrWhiteSpace(entity.ParentId) && entity.ParentId.Equals("0"))
            {
                entity.ParentId = "";
            }
            if (this.IsPost)
            {
                string strError = "";
                if (mSService.Save(entity, ref strError))
                {
                    entity.action = "DBC";
                    if (string.IsNullOrWhiteSpace(entity.ParentId))
                    {
                        entity.parent = "0_S";
                    }
                    else {
                        entity.parent = entity.ParentId + "_0_S";
                    }
                    return Json(AjaxResult.Success(entity));
                }
                return Json(AjaxResult.Error(strError));
            }
            return View(entity);
        }
        [Permission(IsPost = true, ActionName = "SaveColumns")]
        public IActionResult DbTable(DbTableEntity entity,string id)
        {
            if (this.IsPost)
            {
                string strError = "";
                if (mTService.Save(entity, ref strError))
                {
                    return Json(AjaxResult.Success(entity));
                }
                return Json(AjaxResult.Error(strError));
            }
            return View(entity);
        }

        [Permission(IsParent =true)]
        public IActionResult GetColumns(LigerGrid ligerGrid, string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                var dbColumns = mCService.GetColumns(id);
                ligerGrid.Rows = dbColumns;
                if (dbColumns != null)
                {
                    ligerGrid.Total = dbColumns.Count;
                }
            }
            return Json(ligerGrid);
        }
        [HttpPost]
        [Permission(IsParent = true)]
        public JsonResult DbSourceForGrid(LigerGrid grid,string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return Json(grid);
            }
            return Json(mCService.GetDbSource(grid,id));
        }

        /// <summary>
        /// 执行导出并生成文件
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="data"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [Permission("03","导出")]
        public IActionResult Export(LigerGrid grid,string groupWhere, string id)
        {
            if (!string.IsNullOrWhiteSpace(groupWhere))
            {
                grid.Group = JSONHelper.FromJson<GroupFilter>(groupWhere);
            }
            var buffer = mCService.Export(grid, id);
            if (buffer != null&& buffer.Length>0)
            {
                return this.ExportExcel(buffer,  DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
            }
            else
            {
                return Json(AjaxResult.Error("导出失败，请联系管理员"));
            }

        }
        [HttpPost]
        [Permission(ActionName = "SaveColumns")]
        public IActionResult SaveColumnsCell(string id,DbColumnEntity dbColumn)
        {
            string strError = "";
            if (mCService.SaveColumnsCell(id, dbColumn, ref strError))
            {
                return Json(AjaxResult.Success());
            }
            else
            {
                return Json(AjaxResult.Error(strError));
            }
        }

        /// <summary>
        /// 选择目标服务器
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Permission(IsParent =true)]
        public IActionResult SelectTargetDbServer(TargetDbServerModel model)
        {
            return View(mSService.GetTargetDbServer(model));
        }

        //[Permission("04", "导入")]
        //[HttpPost]
        ///// <summary>
        ///// 文件上传
        ///// </summary>
        ///// <returns></returns>
        //public IActionResult Import(string serverid)
        //{
        //  //  string strError = "";
        //    //if (mService.Import(serverid, ref strError))
        //    //{
        //    //    strError = JSONHelper.ToJson(AjaxResult.Success(strError));
        //    //}
        //    //else
        //    //{
        //    //    strError = JSONHelper.ToJson(AjaxResult.Error(strError));
        //    //}
        //    //return ResultImport(strError);
        //    return View();
        //}

        [HttpPost]
        public IActionResult CreateCode(string tableid, string templateid)
        {
            string strResult = "";
            if (mCService.CreateCode(tableid, templateid, ref strResult))
            {
                return Json(AjaxResult.Success(strResult,""));
            }
            return Json(AjaxResult.Error(strResult));
        }

        [HttpPost]
        [Permission(IsParent =true)]
        public IActionResult GetTemplate(string parentid)
        {
            var items = dTService.GetChildren(parentid);
            if (string.IsNullOrWhiteSpace(parentid))
            {
                if (items != null && items.Count > 0)
                {
                    items.ForEach(x => {
                        x.ParentId = "000";
                    });
                }
                return Json(AjaxResult.Success(new {
                    id= "000",
                    text="所有模板",
                    icon= "fa fa-file-code-o",
                    children=items.ToArray()
                }));
            }
            return Json(AjaxResult.Success(items));
        }

        /// <summary>
        /// 批量生成模板
        /// </summary>
        /// <param name="tableid"></param>
        /// <param name="templateid"></param>
        /// <param name="round"></param>
        /// <param name="maxtable"></param>
        /// <returns></returns>
        [HttpPost]
        [Permission("05","批量生成代码")]
        public async Task<IActionResult> CreateCodes(string tableid, string templateid,int round=0, int maxtable =0)
        {
            await mCService.CreateCodes(tableid, templateid, round, maxtable);
            return Json(AjaxResult.Success(ApplicationEnvironments.TempPath + "code.zip",""));
        }
        /// <summary>
        /// 表数据同步
        /// </summary>
        /// <param name="tableid">表名</param>
        /// <param name="ligerGrid">高级查询</param>
        /// <param name="targgetTableName">目标表</param>
        /// <returns></returns>
        [HttpPost]
        [Permission("06", "数据同步")]
        public IActionResult syncTableData(TargetDbServerModel model, LigerGrid ligerGrid)
        {
            return Json(AjaxResult.Success(mCService.syncTableData(model, ligerGrid)));
        }
        [HttpPost]
        [Permission("07", "同步表结构")]
        public IActionResult syncTableStruct(TargetDbServerModel model)
        {
            string strError = "";
            if (mCService.syncTableStruct(model, ref strError))
            {
                return Json(AjaxResult.Success());
            }
            return Json(AjaxResult.Error(strError));

        }

        [HttpGet]
        [Permission("08", "下载导出模板")]
        public IActionResult DownTableTemplate(string id)
        {
            string strError = "";
            string tableName = "";
            var buffer = mCService.DownTableTemplate(id, ref tableName, ref strError);
            return ExportExcel(buffer, tableName + ".xlsx");

        }

        [HttpPost]
        [Permission("04", "导入", IsParent = true)]
        public JsonResult Import(string id,IFormFile file)
        {
            string strError = "";
            if (mCService.Import(id,file, ref strError))
            {
                return Json(AjaxResult.Success(strError));
            }
            return Json(AjaxResult.Error(strError));
        }

        /// <summary>
        /// 执行导出并生成文件
        /// </summary>
        /// <param name="tableid"></param>
        /// <returns></returns>
        [Permission("10", "表结构导出")]
        public IActionResult ExportTable(string id)
        {
            string strError = "";
            var buffer = mCService.ExportTable(id, ref strError);
            if (buffer != null && buffer.Length > 0)
            {
                return this.ExportExcel(buffer, DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
            }
            else
            {
                return Json(AjaxResult.Error("导出失败，请联系管理员"));
            }

        }
        /// <summary>
        /// 执行导出并生成文件
        /// </summary>
        /// <param name="tableid"></param>
        /// <returns></returns>
      
        [Permission(IsParent =true)]
        public IActionResult ExportWordTable(string id)
        {
            string strError = "";
            var buffer = mCService.ExportWordTable(id, ref strError);
            if (buffer != null && buffer.Length > 0)
            {
                return this.ExportExcel(buffer, DateTime.Now.ToString("yyyyMMddHHmmss") + ".docx");
            }
            else
            {
                return Json(AjaxResult.Error("导出失败，请联系管理员"));
            }

        }
        [Permission(IsParent = true)]
        /// <summary>
        /// 获取线程状态
        /// </summary>
        /// <param name="taskId">线程Id</param>
        /// <returns></returns>
        public IActionResult CheckTaskStatus(string taskId)
        {
            string strError = "";
            return Json(AjaxResult.Success(TaskHelper.Instance.GetById(taskId, ref strError)));
        }
    }
}